package com.edu.cdp.controller;
import com.edu.cdp.utils.CodeUtils;
import com.edu.cdp.utils.VerificationCodeUtils;
import com.edu.cdp.common.Result;
import com.edu.cdp.DTO.MailDTO;
import com.edu.cdp.service.CommonService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@Slf4j
@Tag(name = "通用接口")
@RequestMapping("/comment")
public class CommonController {
    @Autowired
    CodeUtils codeUtils;
    @Autowired
    CommonService commonService;
    @PostMapping("/upload")
    @Operation(summary = "文件上传")
    public Result<String> upload(@RequestPart("file") MultipartFile file) {
        String filePath = commonService.upload(file);
        if (filePath != null) {
            return Result.success(filePath);
        } else {
            return Result.error("上传失败");
        }

    }

    @PostMapping("/code")
    @Operation(summary = "获取QQ邮箱验证码")
    public Result<String> mail(@ParameterObject MailDTO mail) {
        String code = VerificationCodeUtils.generateSixDigitCode();
        // 发送邮件
        String subject = "超市收银管理系统用户注册验证码";
        String content = "尊敬的" + mail.getUsername() +"，您的验证码为："
                + code + "，有效时长为1分钟，请勿泄露！" ;
        commonService.sendMail(mail.getEmail(), subject, content);
        //将验证码缓存到哈希映射
        codeUtils.saveCode(mail.getEmail(), code);

        return Result.success(content );
    }
}
